<template>
  <el-dialog v-model="dialogTableVisible" title="识别结果" width="800">
    <el-table :data="gridData">
      <el-table-column property="uid" label="用户" width="150" />
      <el-table-column  label="识别结果">识别成功</el-table-column>
      <!--      <el-table-column property="distance" label="差距" width="200" />-->
    </el-table>

  </el-dialog>

  <div class="publish">
    <video ref="video" id="video" autoplay></video>
    <canvas ref="canvas" style="display: none" id="canvasCamera"></canvas>
    <div v-if="imgSrc" class="img_bg_camera">
      <img  id="imagePreview" :src="imgSrc" class="tx_img"/>
    </div>
    <button @click="OpenCamera">打开摄像头</button>
    <button @click="CloseCamera">关闭摄像头</button>
    <button @click="setImage">拍照</button>
    <button @click="face">识别</button>
  </div>
  <div>
    <input type="file" accept="image/*"   @change="handleFileChange">

  </div>
</template>

<script setup lang="ts">
import {base64toBlob} from "@/utils/utils.js";
import {onMounted, reactive, ref} from "vue";
import {uploadFaceApi} from "@/api/face";
import {loginApi} from "@/api/login";
import {setRole, setToken} from "@/utils/auth";
import {ElMessage} from "element-plus";
const dialogTableVisible = ref(false)
const gridData = ref([])

const mediaStreamTrack = ref({})
const video_stream = ref('') // 视频stream
const imgSrc = ref('') // 拍照图片
const imgSrcBase64 = ref<any>('') // 拍照图片
const canvas = ref<any>([] as any)
const context = ref<any>('' as any)
const cancas = ref(null)
const photo = ref(null)
const video = ref('' as any)
const formQuery = reactive({
  ugroup: 'usergroup',
  imagefile: '' as any
})


onMounted(() => {
  // 进入页面 自动调用摄像头
  getCamera();
})

//  base64toBlob,
function handleFileChange(event: any) {

  const file = event.target.files[0];
  if (file) {
    displayPhoto(file);
  }
}


function displayPhoto(dataURL: any) {
  imgSrc.value = dataURL;
  console.log(dataURL)
  formQuery.imagefile = dataURL


  const reader = new FileReader();

  // 定义读取完成时的回调函数
  reader.onload = () => {
    // 设置Base64数据
    imgSrc.value = reader.result as any;
  };

  // 读取文件内容，将结果以 data URL 的形式返回
  reader.readAsDataURL(dataURL);


}

// 调用打开摄像头功能
function getCamera() {
  // 获取 canvas 画布
  canvas.value = document.getElementById('canvasCamera');
  context.value = canvas.value.getContext('2d');
  // // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
  // if (navigator.mediaDevices === undefined) {
  //   navigator.mediaDevices = {};
  // }
  // 正常支持版本
  navigator.mediaDevices
      .getUserMedia({
        video: true,
      })
      .then((stream: any) => {
        // 摄像头开启成功
        mediaStreamTrack.value = typeof stream.stop === 'function' ? stream : stream.getTracks()[0];
        video_stream.value = stream;
        video.value.srcObject = stream;
        video.value.play();
      })
      .catch(err => {
        console.log(err);
      });
}

function face() {
  uploadFace()
}

// 拍照 绘制图片
function setImage() {
  console.log('拍照');
  // 点击canvas画图
  context.value.drawImage(
      video.value,
      10,
      10,
      200,
      100,
  );
  // 获取图片base64链接
  imgSrc.value = canvas.value.toDataURL('image/png');
  let filename = (new Date()).valueOf() + Math.round(Math.random() * 1000) + ".png";
// 将 Base64 字符串转换为 Blob
  const byteCharacters = atob(imgSrc.value.split(',')[1]);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  const blob = new Blob([byteArray], {type: 'image/png'}); // 替换为实际的 MIME 类型
  //base64toBlob(imgSrc.value, 'image/png', filename)
  formQuery.imagefile = new File([blob], filename, {type: blob.type});
  uploadFace()
}
function uploadFace(){
  uploadFaceApi(formQuery).then((response: any) => {
    if (response.state=== "success, but not match face" ){
      ElMessage.warning('识别成功，但是无匹配对象')

    }else {

      ElMessage.success('识别成功')
      console.log(response)
      dialogTableVisible.value = true
      gridData.value = response

    }

  }).catch((res: any) => {
  }).finally(() => {
  })
}

// 打开摄像头
function OpenCamera() {
  console.log('打开摄像头');
  getCamera();
}

// 关闭摄像头
function CloseCamera() {
  console.log('关闭摄像头');
  video.value.srcObject.getTracks()[0].stop();
}
</script>

<style lang="scss" scoped>
video {
  width: 100%;
  height: 300px;
}


canvas {
  width: 100%;
  height: 300px;
}

button {
  width: 100px;
  height: 40px;
  position: relative;
  bottom: 0;
  left: 0;
  background-color: rgb(22, 204, 195);
}

.img_bg_camera {
  img {
    width: 300px;
    height: 200px;
  }
}
</style>
